﻿using System;
using System.Collections.Generic;
using System.Text;

using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using iTool.SQL.Analysis.Context.SQLWhereOptions;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace iTool.SQL.Analysis.Common
{
    public class SqlAggregateFunctionCallExpressionAnalysis : SqlAnalysisBase
    {
        public SqlAggregateFunctionCallExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            // where
            // set
            // select
            var aggregate = (SqlAggregateFunctionCallExpression)base.CodeObject;
            var where = (WhereOptions)base.WhereOptions;
            switch (base.CodeObject.Parent)
            {
                case var t when t is SqlSelectScalarExpression || base.CodeObject.Parent.Parent is SqlSelectScalarExpression:
                    ((SqlSelectAnalysisContext)base.context).QueryFields.Add(new Context.Options.SQLFieldOptions
                    {
                        FN = aggregate.FunctionName
                    });
                    base.Next();
                    break;

                case var t when t is SqlColumnAssignment:
                    ((SqlUpdateAnalysisContext)base.context).Sets[^1].Value = aggregate.FunctionName + "(";
                    base.Next();
                    return;

                default:

                    var fieldOptions = new SQLFieldOptions { FN = aggregate.FunctionName };
                    if (where.Left == null)
                        where.Left = fieldOptions;
                    else if (where.Right == null)
                        where.Right = fieldOptions;

                    //StringBuilder where = base.GetWhereBuilder();
                    //where.Append(aggregate.FunctionName);
                    //where.Append("(");
                    base.Next(whereProperty: fieldOptions);
                    //where.Append(")");
                    return;
            }
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
